package controllers

import (
	"centerServer/compnents"
	"centerServer/models"
	"encoding/json"
	"github.com/astaxie/beego"
	"strconv"
)

type UserShareController struct {
	beego.Controller
}

func (this *UserShareController) Get()  {
	requestInfo := models.UserShareRequest{}
	backMsg := models.CreatorBackBase(0, "")
	if err := this.ParseForm(&requestInfo); err != nil {
		//handle error
		backMsg.ReturnCode = -1
		backMsg.Msg = "参数解析错误" + err.Error()
		backData, _ := json.Marshal(backMsg)
		this.Ctx.Output.Body(backData)
		return
	}
	// 检测签名
	checkSignMap := requestInfo.GetSignInfos()
	if compnents.CheckSign(checkSignMap, requestInfo.Sign) == false {
		backMsg.ReturnCode = -1
		backMsg.Msg = "签名错误"
		backData, _ := json.Marshal(backMsg)
		this.Ctx.Output.Body(backData)
		return
	}
	// 查询用户的unionID
	requstCode2Session, rErr := compnents.WxCode2SessionA(requestInfo.WxCode)
	if rErr != nil || requstCode2Session.ErrorCode != 0 {
		backMsg.ReturnCode = -1
		backMsg.Msg = "请求UnionID失败,ErrorCode:" + strconv.Itoa(requstCode2Session.ErrorCode)
		backData, _ := json.Marshal(backMsg)
		this.Ctx.Output.Body(backData)
		return
	}
	requestUserInfo, rErr := compnents.WXGetUserInfo(requstCode2Session.AccessToken, requstCode2Session.Openid)
	if rErr != nil || requestUserInfo.ErrorCode != 0 {
		backMsg.ReturnCode = -1
		backMsg.Msg = "请求用户信息失败,ErrorCode:" + strconv.Itoa(requstCode2Session.ErrorCode)
		backData, _ := json.Marshal(backMsg)
		this.Ctx.Output.Body(backData)
		return
	}
	// 插入数据库
	uData := models.UserShareInfo{}
	uData.UnionId = requestUserInfo.UnionId
	uData.InviteCode = requestInfo.InviteCode
	uData.WriteToDB()
	backData, _ := json.Marshal(backMsg)
	this.Ctx.Output.Body(backData)
}